package org.wit.ecommerce.dao;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.Query;
import org.wit.ecommerce.domain.Product;
/**
 * @spring.bean id="productDao"
 * @spring.property name="sessionFactory" ref="sessionFactoryObj"
 * @author Justin
 *
 */
public class ProductDao extends SimpleHibernateDao<Product, Long> {
	/**
	 * find entities by page and criteria
	 * @author Justin
	 */
	@SuppressWarnings("unchecked")
	public List<Product> findByPage(int start, int limit, Map<String, ?> keywords){
		String select = "from org.wit.ecommerce.domain.Product where 1=1 ";
		String hql = addKeywords(new StringBuffer(select), keywords);
		Query query = createQuery(hql);
		query.setFirstResult(start);
		query.setMaxResults(limit);
		return query.list();
	}
	
	/**
	 * return total rows
	 * @author Justin
	 * @param keywords
	 * @return
	 */
	public int getTotalCount(Map<String, ?> keywords){
		String select = "select count(*) from org.wit.ecommerce.domain.Product where 1=1 ";
		String hql = addKeywords(new StringBuffer(select), keywords);
		Query query = createQuery(hql);
		return ((Number) query.uniqueResult()).intValue();
	}
	
	private String addKeywords(StringBuffer sb, Map<String, ?> keywords){
		String name = (String)keywords.get("name");
		BigDecimal minPrice = (BigDecimal)keywords.get("minPrice");
		BigDecimal maxPrice = (BigDecimal)keywords.get("maxPrice");
		
		if(StringUtils.isNotBlank(name)){
			sb.append(" and name = '").append(name).append("'");
		}
		if(minPrice != null){
			sb.append(" and minPrice >= ").append(minPrice);
		}
		if(maxPrice != null){
			sb.append(" and maxPrice <= ").append(maxPrice);
		}
		return sb.toString();
	}
}
